package org.tinygroup.wssample.endpoint;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import org.tinygroup.wssample.service.CourseService;
import org.tinygroup.wssample.service.exception.CourseNotFoundException;
import org.tinygroup.wssample.types.Course;
import org.tinygroup.wssample.types.GetCourseListRequest;
import org.tinygroup.wssample.types.GetCourseListResponse;
import org.tinygroup.wssample.types.GetCourseRequest;
import org.tinygroup.wssample.types.GetCourseResponse;

@Endpoint
public class CourseEndpoint {
	private static final String NAMESPACE = "http://www.xpadro.spring.samples.com/courses";

	@Autowired
	private CourseService service;

	@PayloadRoot(localPart = "getCourseRequest", namespace = NAMESPACE)
	public @ResponsePayload GetCourseResponse getCourse(
			@RequestPayload GetCourseRequest request) {
		Course course = service.getCourse(request.getCourseId());

		if (course == null) {
			throw new CourseNotFoundException("course ["
					+ request.getCourseId() + "] does not exist");
		}

		GetCourseResponse response = new GetCourseResponse();
		response.setCourseId(course.getCourseId());
		response.setDescription(course.getDescription());
		response.setName(course.getName());
		response.setSubscriptors(course.getSubscriptors());

		return response;
	}

	@PayloadRoot(localPart = "course", namespace = NAMESPACE)
	public @ResponsePayload Course handle(@RequestPayload Course course) {
		System.out.println(course.getCourseId());
		System.out.println(course.getName());
		course.setCourseId("ddsdsf");
		;
		course.setName("Hello Spring!");
		return course;
	}

	@PayloadRoot(localPart = "getCourseListRequest", namespace = NAMESPACE)
	public @ResponsePayload GetCourseListResponse getCourseList(
			@RequestPayload GetCourseListRequest request) {
		GetCourseListResponse response = new GetCourseListResponse();
		for (Map.Entry<String, Course> entry : service.getCourses().entrySet()) {
			response.getCourse().add(entry.getValue());
		}

		return response;
	}
}
